package com.hengxinguotong.zhihuichengjian.utils;

import android.annotation.TargetApi;
import android.app.ActivityManager;
import android.content.Context;
import android.os.Build;
import android.os.Debug;
import android.util.Log;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.List;

import static android.content.Context.ACTIVITY_SERVICE;

/**
 * Created by Administrator on 2017/8/14.
 */

public class CacheManager {
    /**
     * 用于获取手机可用内存
     */
    private static ActivityManager mActivityManager;

    /**
     * 如果ActivityManager还未创建，则创建一个新的ActivityManager返回。否则返回当前已创建的ActivityManager。
     *
     * @param context
     *            可传入应用程序上下文。
     * @return ActivityManager的实例，用于获取手机可用内存。
     */
    private static ActivityManager getActivityManager(Context context) {
        if (mActivityManager == null) {
            mActivityManager = (ActivityManager) context.getSystemService(ACTIVITY_SERVICE);
        }
        return mActivityManager;
    }

    /**
     * 计算已使用内存的百分比，并返回。
     *
     * @param context
     *            可传入应用程序上下文。
     * @return 已使用内存，以字符串形式返回。
     */
    public static String getUsedPercentValue(Context context) {
        String dir = "/proc/meminfo";
        try {
            FileReader fr = new FileReader(dir);
            BufferedReader br = new BufferedReader(fr, 2048);
            String memoryLine = br.readLine();
            String subMemoryLine = memoryLine.substring(memoryLine.indexOf("MemTotal:"));
            br.close();
            long totalMemorySize = Integer.parseInt(subMemoryLine.replaceAll("\\D+", ""))/1024;
            long availableSize = getAvailableMemory(context) / 1024/1024;
            double percent = (double) (totalMemorySize - availableSize)/1024;
            DecimalFormat df=new java.text.DecimalFormat("#.##");
            return df.format(percent) + "M";
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "0M";
    }

    /**
     * 获取当前可用内存，返回数据以字节为单位。
     *
     * @param context
     *            可传入应用程序上下文。
     * @return 当前可用内存。
     */
    private static long getAvailableMemory(Context context) {
        ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
        getActivityManager(context).getMemoryInfo(mi);
        return mi.availMem;
    }

    /**
     * 获取内存信息
     * @return
     */
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    public static String getCurrentMeminfo(Context context) {
        StringBuffer sb = new StringBuffer();
        ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
        ActivityManager activityManager = (ActivityManager) context.getSystemService(ACTIVITY_SERVICE);
        activityManager.getMemoryInfo(mi);
        long availMem = (mi.availMem/1024/1024) ;//剩余内存
        long totalMem = 0;
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            totalMem = (mi.totalMem/1024/1024);//总内存
        }
        boolean lowMemory = mi.lowMemory;//内存是否过低
        return totalMem - availMem + "MB\n";
    }

    private static String LOG_TAG = "cleaner";
    /**
     * 清理内存
     */
    public static  void clearMem(Context context) {
        ActivityManager activityManger = (ActivityManager) context.getSystemService(ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> appList = activityManger.getRunningAppProcesses();
        if (appList != null) {
            for (int i = 0; i < appList.size(); i++) {
                ActivityManager.RunningAppProcessInfo appInfo = appList.get(i);

                Log.v(LOG_TAG, "pid: " + appInfo.pid);
                Log.v(LOG_TAG, "processName: " + appInfo.processName);
                Log.v(LOG_TAG, "importance: " + appInfo.importance);

                String[] pkgList = appInfo.pkgList;
                if (appInfo.importance > ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE) {
                    for (int j = 0; j < pkgList.length; j++) {
                        activityManger.killBackgroundProcesses(pkgList[j]);
                    }
                }
            }
        }
    }

    //获取本应用占用内存的方法：
    @TargetApi(Build.VERSION_CODES.KITKAT)
    public static int getMemory() {
        Debug.MemoryInfo memoryInfo = new Debug.MemoryInfo();
        Debug.getMemoryInfo(memoryInfo);
        // dalvikPrivateClean + nativePrivateClean + otherPrivateClean;
        int totalPrivateClean = memoryInfo.getTotalPrivateClean();
        // dalvikPrivateDirty + nativePrivateDirty + otherPrivateDirty;
        int totalPrivateDirty = memoryInfo.getTotalPrivateDirty();
        // dalvikPss + nativePss + otherPss;
        int totalPss = memoryInfo.getTotalPss();
        // dalvikSharedClean + nativeSharedClean + otherSharedClean;
        int totalSharedClean = memoryInfo.getTotalSharedClean();
        // dalvikSharedDirty + nativeSharedDirty + otherSharedDirty;
        int totalSharedDirty = memoryInfo.getTotalSharedDirty();
        // dalvikSwappablePss + nativeSwappablePss + otherSwappablePss;
        int totalSwappablePss = memoryInfo.getTotalSwappablePss();

        int total = totalPrivateClean + totalPrivateDirty + totalPss + totalSharedClean + totalSharedDirty + totalSwappablePss;
        return total/1024 ;
    }

//    private void getRunningAppProcessInfo(Context context) {
//        mActivityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
//
//        //获得系统里正在运行的所有进程
//        List<runningappprocessinfo> runningAppProcessesList = mActivityManager.getRunningAppProcesses();
//
//        for (RunningAppProcessInfo runningAppProcessInfo : runningAppProcessesList) {
//            // 进程ID号
//            int pid = runningAppProcessInfo.pid;
//            // 用户ID
//            int uid = runningAppProcessInfo.uid;
//            // 进程名
//            String processName = runningAppProcessInfo.processName;
//            // 占用的内存
//            int[] pids = new int[] {pid};
//            Debug.MemoryInfo[] memoryInfo = mActivityManager.getProcessMemoryInfo(pids);
//            int memorySize = memoryInfo[0].dalvikPrivateDirty;
//
//            System.out.println("processName="+processName+",pid="+pid+",uid="+uid+",memorySize="+memorySize+"kb");
//        }
//    }
}